package com.tt.vtg.scenario.http.encoder;

import com.tt.vtg.scenario.http.HttpJsonResponse;
import com.tt.vtg.scenario.http.pojo.ResponseEntity;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.util.List;

public class HttpJsonResponseEncoder extends AbstractHttpJsonEncoder<HttpJsonResponse<ResponseEntity>> {
    @Override
    protected void encode(ChannelHandlerContext ctx, HttpJsonResponse<ResponseEntity> msg, List<Object> out) throws Exception {
//        System.out.println("HttpJsonResponseEncoder...");
        FullHttpResponse response = msg.getHttpResponse();
        ByteBuf body = _encode(msg.getObj());

        if(response == null) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, body);
        } else {
            response = new DefaultFullHttpResponse(msg.getHttpResponse().protocolVersion(),
                    msg.getHttpResponse().status(),
                    body);
        }

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/json");
        HttpUtil.setContentLength(response, body.readableBytes());
        out.add(response);
    }
}
